package mysql

import (
	"mxshop_srvs/userop_srv/model"
	proto "mxshop_srvs/userop_srv/proto/gen/v1"
)

func (g *Gorm) GetAddresses(userID int32) ([]model.Address, error) {
	addresses := make([]model.Address, 0, 8)
	err := g.db.Model(&model.Address{}).Where(&model.Address{
		UserID: userID,
	}).Find(&addresses).Error
	return addresses, err
}

func (g *Gorm) GetAddress(ID, userID int32) (model.Address, error) {
	var address model.Address
	err := g.db.Where(&model.Address{UserID: userID}, "UserID").Take(&address, ID).Error
	return address, err
}

func (g *Gorm) CreateAddress(req *proto.Address) (uint, error) {
	var address = model.Address{
		UserID:       req.UserId,
		Province:     req.Province,
		City:         req.City,
		District:     req.District,
		Address:      req.Address,
		SignerName:   req.SignerName,
		SignerMobile: req.SignerMobile,
	}
	err := g.db.Create(&address).Error
	return address.ID, err
}

func (g *Gorm) DeleteAddress(ID, userID int32) (int64, error) {
	result := g.db.Where(&model.Address{UserID: userID}, "UserID").Delete(&model.Address{}, ID)
	return result.RowsAffected, result.Error
}

func (g *Gorm) UpdateAddress(req *proto.AddressEntity) (int64, error) {
	address, err := g.GetAddress(req.Id, req.Address.UserId)
	if err != nil {
		return 0, err
	}

	result := g.db.Model(&address).Updates(model.Address{
		UserID:       req.Address.UserId,
		Province:     req.Address.Province,
		City:         req.Address.City,
		District:     req.Address.District,
		Address:      req.Address.Address,
		SignerName:   req.Address.SignerName,
		SignerMobile: req.Address.SignerMobile,
	})

	return result.RowsAffected, result.Error
}
